<?php
/**
 * Created by PhpStorm.
 * User: zmit
 * Date: 8/5/17
 * Time: 7:56 PM
 */
namespace ApiBundle\Controller\Platform;

use ApiBundle\Controller\BaseController;

use Symfony\Component\HttpFoundation\Request;

class DistrictController extends BaseController
{
    /*
     * 获取区域列表
     */
    public function districtListAction(Request $request)
    {
        $conn = $this->get("database_connection");

        $page = $request->get("page","1");

        $rows = $request->get("rows","10");

        $district_name = $request->get("district_name");

        $sql = "SELECT * FROM district WHERE 1";

        // 搜索
        if(!empty($district_name)){
            $sql .= " AND name = '". $district_name ."' ";
        }

        $search_all_count = count($conn->fetchAll($sql));

        $all_page = ceil($search_all_count / $rows);

        // 分页
        $m = ($page -1) * $rows;

        $sql .= " LIMIT $m,$rows ";


        $data = $conn->fetchAll($sql);

        return $this->jsonResponse(0,"操作成功",array("info" => $data,"search_all_count"=>$search_all_count,"all_page"=>$all_page));

    }

    /*
     * 编辑/添加区域
     */
    public function editDistrictAction(Request $request)
    {
        if(!$this->isPlatAdminLogged()){
            return $this->plat_response;
        }
        $conn = $this->get("database_connection");
        $id = $request->get("id");
        $district = $request->get("district");

        if(empty($district)){
            return $this->jsonResponse(1,"区域不能为空");
        }

        $district = $this->strFilter($district);
        if(empty($district)){
            return $this->jsonResponse(1,"区域不能为特殊字符");
        }


        // 编辑时，获取原勋章名称
        $origin_name = $conn->fetchAssoc("SELECT * FROM district WHERE id = '". $id ."'");
        if($origin_name['name'] != $district){

            // 判断区域是否存在
            $is_exit = $conn->fetchAssoc("SELECT * FROM district WHERE name = '". $district ."'");

            if($is_exit){
                return $this->jsonResponse(1,"该区域已存在");
            }
        }


        $data = array("name" => $district);
        if(empty($id)){

            $data['created_at'] = date("Y-m-d H:i:s");
            $conn->insert("district",$data);

        } else {
            $where = array("id" => $id);
            $data['updated_at'] = date("Y-m-d H:i:s");
            $conn->update("district",$data,$where);
        }

        return $this->jsonResponse(0,"操作成功");

    }

    /*
     * 删除区域
     */
    public function deleteDistrictAction(Request $request)
    {
        if(!$this->isPlatAdminLogged()){
            return $this->plat_response;
        }

        $conn = $this->get("database_connection");
        $id = $request->get("id");

        if(empty($id)){
            return $this->jsonResponse(1,"参数错误");
        }

        $where = array("id" => $id);

        $conn->delete("district",$where);
        return $this->jsonResponse(0,"操作成功");
    }

}